
$(document).ready
(
	function () 
	{
		// add an on-click to the signup checkbox
		$("#lb_signup_checkbox").click
		(
			function ()
			{
				if (this.checked)
				{
					showSignupUI ();
				}
				else
				{
					hideSignupUI ();
				}

				focusFirstEmptyField ();
			}
		);

		// add an on-click to the signup checkbox
		$("#lb_forgot_password_checkbox").click
		(
			function ()
			{
				if (this.checked)
				{
					showResetPasswordUI ();
				}
				else
				{
					hideResetPasswordUI ();
				}

				focusFirstEmptyField ();
			}
		);
	}
);

// no session, get the creds from the form and get the token
function
authenticate (inForm)
{
	var	userName = inForm.username.value;

	if (userName == null || userName.length == 0)
	{
		$("#lb_auth_error").html ('Please enter user name.');
		inForm.username.focus ();
		return false;
	}
	
	var	password = inForm.password.value;
	
	if (password == null || password.length == 0)
	{
		$("#lb_auth_error").html ('Please enter password.');
		inForm.password.focus ();
		return false;
	}
	
	var	authenticateURL = null;
	var	parameters = {};
	
	if ($("#lb_signup_checkbox").attr ("checked"))
	{
		var	email = inForm.email.value;
		
		if (email == null || email.length == 0)
		{
			$("#lb_auth_error").html ('Please enter email address.');
			inForm.email.focus ();
			return false;
		}

		if (! isValidEmailAddress (email))
		{
			$("#lb_auth_error").html ('Please enter valid email address.');
			inForm.email.focus ();
			return false;
		}
		
		// the flag here is "disallow blank dates"
		if (! validateDate (inForm, false))
		{
			return false;
		}

		authenticateURL = 'servlet/SignupServlet';
		parameters.email = inForm.email.value;
		parameters.year = inForm.year.value;
		parameters.month = inForm.month.value;
		parameters.day = inForm.day.value;
	}
	else
	{
		// did we make the birthdate container visible
		// perhaps due to a failed authentication as there wasn't a birthdate
		// in the Brother record?
		if ($("#lb_birthdate_container").is (":visible"))
		{
			// the flag here is "allow blank dates"
			// because the user may have entered different credentials
			// (ie ones which *do* have a birthdate)
			if (! validateDate (inForm, true))
			{
				return false;
			}

			parameters.year = inForm.year.value;
			parameters.month = inForm.month.value;
			parameters.day = inForm.day.value;
		}
		
		authenticateURL = 'servlet/SigninServlet?';
	}

	parameters.username = userName;
	parameters.password = password;
	parameters.site = inForm.site.value;

	if (typeof (inForm.page) != 'undefined')
	{
		parameters.page = inForm.page.value;
	}
	
	$("#lb_auth_progress").show ();
	
	$.post (authenticateURL, parameters, receiveAuthenticate, 'json');

	// do NOT submit the form
	return false;
}

function
getErrorMessage (inJSON)
{
	var	message = 'Cannot determine call status!';
	
	if (inJSON.exception == undefined)
	{
		if (gErrorMap != undefined)
		{
			message = gErrorMap ['LbAuthenticationException'];
			
			if (message == undefined)
			{
				message = 'Authentication failure.';
			}
		}
	}
	else
	{
		message = undefined;
		
		if (gErrorMap != undefined)
		{
			var	message = gErrorMap [inJSON.exception];

			if (message == undefined)
			{
				message = gErrorMap ['default'];
			}
			else
			{
				var	parameters = [];
				
				if (inJSON.message != undefined)
				{
					parameters [0] = inJSON.message;
				}

				message = parameteriseString (message, parameters);
			}
		}

		if (message == undefined)
		{
			if (inJSON.message == undefined)
			{
				message = inJSON.exception;
			}
			else
			{
				message = inJSON.exception + ': ' + inJSON.message;
			}
		}
	}
	
	return message;
}

function
focusFirstEmptyField ()
{
	// focus on the first empty field
	var	value = $("#lb_username_field").attr ('value');
	
	if (value == null || value.length == 0)
	{
		$("#lb_username_field").focus ();
	}
	
	if (value.length > 0)
	{
		value = $("#lb_password_field").attr ('value');
		
		if (value == null || value.length == 0)
		{
			$("#lb_password_field").focus ();
		}
	}

	if (value.length > 0 && $("#lb_email_container").is (":visible"))
	{
		value = $("#lb_email_field").attr ('value');
		
		if (value == null || value.length == 0)
		{
			$("#lb_email_field").focus ();
		}
	}
}

function
hideResetPasswordUI ()
{
	// reinstall the configured auth button label
	$("#lb_form_submit").attr ('value', submitButtonText);
	
	// update the form target
	$('#lb_auth_form').attr ('onSubmit', 'return authenticate (this)');
	
	$("#lb_password_container").show ();
	$("#lb_email_container").hide ();
	$("#lb_signup_container").show ();

	if (typeof (onShowAuthentication) != 'undefined')
	{
		onShowAuthentication ();
	}
}

function
hideSignupUI ()
{
	$("#lb_email_container").hide ();
	$("#lb_birthdate_container").hide ();
	$("#lb_forgot_password_checkbox_container").show ();
	
	if (typeof (onShowAuthentication) != 'undefined')
	{
		onShowAuthentication ();
	}
}

function
isLeapYear (inYear)
{
	var	leap = false;
	
	if ((inYear % 400) == 0)
	{
		leap = true;
	}
	else
	{
		if ((inYear % 4 == 0) && (inYear % 100 != 0))
		{
			leap = true;
		}
	}
	
	return leap;
}

// swiped from the intarweb, i take no responsibility :-)
function
isValidEmailAddress (inEmailAddress)
{
	var	pattern = new RegExp(/^(("[\w\s+-]+")|([\w+-]+(?:\.[\w+-]+)*)|("[\w\s+-]+")([\w+-]+(?:\.[\w+-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test (inEmailAddress);
}

// HACK inefficient
function
parameteriseString (inString, inParameters)
{
	var	newString = inString;
	
	for (var i = 0; i < inParameters.length; i++)
	{
		newString = newString.replace ('{' + i + '}', inParameters [i]);
	}
	
	return newString;
}

function
receiveAuthenticate (inJSON)
{
	$("#lb_auth_error").html ('');
	$("#lb_auth_progress").hide ();
	
	if (inJSON.response == 'cool')
	{
		// the signin/signup servlet returns a site-specific URL
		parent.location = inJSON.location;
	}
	else
	{
		// check for a missing birthdate and expose the UI
		if (inJSON.exception == 'LbValidationException'
			&& inJSON.message == 'birthdate')
		{
			$("#lb_birthdate_container").show ();
			$("#lb_birth_year_field").focus ();
			
			if (typeof (onShowBirthdate) != 'undefined')
			{
				onShowBirthdate ();
			}
		}
		else
		{
			$("#lb_auth_error").html (getErrorMessage (inJSON));
			$("#lb_auth_error").show ();
		}
	}
}

function
receiveResetPassword (inJSON)
{
	$("#lb_auth_error").html ('');
	$("#lb_auth_progress").hide ();
	
	if (inJSON.response == 'cool')
	{
		$("#lb_auth_error").html ('Check your email for your login information.');
	}
	else
	{
		if (inJSON.exception != null && inJSON.exception.length != 0)
		{
			$("#lb_auth_error").html (getErrorMessage (inJSON));
		}
		else
		{
			$("#lb_auth_error").html ('Could not find your account, sorry.');
		}
	}

	$("#lb_auth_error").show ();
}

function
receiveUpdate (inJSON)
{
	$("#lb_update_error").html ('');
	$("#lb_update_progress").hide ();
	
	if (inJSON.response == 'cool')
	{
		// the signin/signup servlet returns a site-specific URL
		parent.location = inJSON.location;
	}
	else
	{
		$("#lb_update_error").html (getErrorMessage (inJSON));
		$("#lb_update_error").show ();
	}
}

function
resetPassword (inForm)
{
	var	email = inForm.email.value;

	if (email == null || email.length == 0)
	{
		$("#lb_auth_error").html ('Please enter user name and email address.');
		inForm.username.focus ();
		return false;
	}

	var	resetPasswordURL = null;
	var	parameters = {};
	
	resetPasswordURL = 'servlet/ResetPasswordServlet';
	parameters.email = email;
	parameters.site = inForm.site.value;

	$("#lb_auth_progress").show ();
	
	$.post (resetPasswordURL, parameters, receiveResetPassword, 'json');
	
	// do NOT submit the form
	return false;
}

function
showResetPasswordUI ()
{
	$("#lb_form_submit").attr ('value', 'Reset Password');
	
	// update the form target
	$('#lb_auth_form').attr ('onSubmit', 'return resetPassword (this)');
	
	$("#lb_email_container").show ();
	$("#lb_signup_container").hide ();
	$("#lb_password_container").hide ();
	
	$("#lb_username_field").focus ();

	if (typeof (onShowResetPassword) != 'undefined')
	{
		onShowResetPassword ();
	}
}

function
showSignupUI ()
{
	$("#lb_email_container").show ();
	$("#lb_birthdate_container").show ();
	$("#lb_forgot_password_checkbox_container").hide ();
	
	if (typeof ('onShowSignup') != 'undefined')
	{
		onShowSignup ();
	}
}

function
update (inForm)
{
	var	password = inForm.password.value;
	
	// password must be there to update anything
	if (password == null || password.length == 0)
	{
		$("#lb_auth_error").html ('Please enter existing password to update information.');
		inForm.password.focus ();
		return false;
	}
	
	var	updating = false;
	
	var	newUserName = inForm.new_username.value;
	
	if (newUserName == null || newUserName.length == 0)
	{
		// not updating the user name, then
	}
	else
	{
		updating = true;
	}

	var	newPassword = inForm.new_password.value;
	
	if (newPassword == null || newPassword.length == 0)
	{
		// not updating the password, then
	}
	else
	{
		updating = true;
	}

	var	newEmail = inForm.new_email.value;
	
	if (newEmail == null || newEmail.length == 0)
	{
		// not updating the email address, then
	}
	else
	{
		if (! isValidEmailAddress (newEmail))
		{
			$("#lb_auth_error").html ('Please enter valid email address.');
			inForm.new_email.focus ();
			return false;
		}
		
		updating = true;
	}
	
	if (!updating)
	{
		return false;
	}
	
	var	updateURL = 'servlet/UpdateServlet';

	var	parameters = {};
	parameters.username = inForm.username.value;
	parameters.password = password;
	parameters.newusername = newUserName;
	parameters.newpassword = newPassword;
	parameters.newemail = newEmail;
	
	parameters.site = inForm.site.value;

	if (typeof (inForm.page) != 'undefined')
	{
		parameters.page = inForm.page.value;
	}
	
	$("#lb_update_progress").show ();
	
	$.post (updateURL, parameters, receiveUpdate, 'json');

	// do NOT submit the form
	return false;
}

function
validateDate (inForm, inAllowBlankDates)
{
	var	year = inForm.year.value;
	var	month = inForm.month.value;
	var	day = inForm.day.value;
	
	// if the date is blank, and we allow blank dates, succeed early
	if ((year == null || year.length == 0)
		&& (month == null || month.length == 0)
		&& (day == null || day.length == 0))
	{
		if (inAllowBlankDates)
		{
			return true;
		}
	}
	
	// validate Y > M > D
	// as we can't validate a day without a year *and* a month
	var	currentYear = new Date ().getFullYear ();
	var	jailbaitYear = currentYear - 13;
	
	if (year == null || year.length == 0
		|| isNaN (parseInt (year))
		|| parseInt (year) < 1900
		|| parseInt (year) > currentYear)
	{
		
		$("#lb_auth_error").html ('Please enter valid year (1900-' + jailbaitYear + ').');
		inForm.year.focus ();
		return false;
	}
	
	if (month == null || month.length == 0
		|| isNaN (parseInt (month))
		|| parseInt (month) < 1
		|| parseInt (month) > 12)
	{
		$("#lb_auth_error").html ('Please enter valid month (1-12).');
		inForm.month.focus ();
		return false;
	}
	
	var	dayLimit = 31;
	
	if (month == 2)
	{
		if (isLeapYear (year))
		{
			dayLimit = 29;
		}
		else
		{
			dayLimit = 28;
		}
	}
	else
	if (month == 4 || month == 6 || month == 11)
	{
		dayLimit = 30;
	}
	
	if (day == null || day.length == 0
		|| isNaN (parseInt (day))
		|| day < 1
		|| day > dayLimit)
	{
		$("#lb_auth_error").html ('Please enter valid day (1-' + dayLimit + ').');
		inForm.day.focus ();
		return false;
	}

	return true;		
}

